<?php

/*
	info: 文件上传处理类
	base: WEB_TIME, FileSystem, TimeDate, String, $webUpfile
	$Id: upload.class.php 13 2011-03-25 08:33:49Z lfly1573@gmail.com $
*/

if (!defined('WEB_IN'))
{
	header("HTTP/1.0 404 Not Found");
	exit();
}

class Upload
{
	public $errorMsg = '';
	public $fileList = array();
	public $fileNum = 0;

	private $upConfig = array('type'=>array(), 'notype'=>array(), 'totype'=>array('php','phtml','php3','php4','jsp','asp','cer','asa','shtml','shtm','aspx','asax','cgi','fcgi','pl','exe','dll','reg','bat','com'), 'size'=>0);
	private $upData = array();


	/**
	 * 构造函数 初始化上传控件和上传条件
	 * @param $strInputName 上传的input名称
	 * @param $aryConfig 上传参数配置
	 * @return void
	 */
	public function __construct($strInputName = '', $aryConfig = array())
	{
		if ($strInputName != '')
		{
			$this->SetInput($strInputName);
			if (!empty($aryConfig))
			{
				$this->SetConfig($aryConfig);
			}
		}
	}

	/**
	 * 检测上传的文件
	 * @return bool 上传文件是否合法
	 */
	public function CheckFile()
	{
		if (!is_array($this->upData) || empty($this->upData))
		{
			$this->errorMsg = 'lang:uploadNotHaveFile';
			return FALSE;
		}
		foreach ($this->upData as $key => $attach)
		{
			if (!$this->IsUploadedFile($attach['tmp_name']) || !($attach['tmp_name']!='none' && $attach['tmp_name'] && $attach['name']))
			{
				$this->errorMsg = 'lang:uploadNotHaveFile';
				return FALSE;
			}

			if (isset($attach['error']) && $attach['error']>0)
			{
				$this->errorMsg = "lang:uploadFailed@@{$attach['name']}";
				return FALSE;
			}

			$attach['ext'] = FileSystem::GetFileExt($attach['name'], FALSE);
			if (empty($attach['ext']))
			{
				$this->errorMsg = "lang:uploadInvalidFile@@{$attach['name']}";
				return FALSE;
			}
			elseif (is_array($this->upConfig['type']) && !empty($this->upConfig['type']) && !in_array($attach['ext'], $this->upConfig['type']))
			{
				$this->errorMsg = "lang:uploadNotAllowType@@{$attach['name']}";
				return FALSE;
			}
			elseif (is_array($this->upConfig['notype']) && !empty($this->upConfig['notype']) && in_array($attach['ext'], $this->upConfig['notype']))
			{
				$this->errorMsg = "lang:uploadNotAllowType@@{$attach['name']}";
				return FALSE;
			}

			if (empty($attach['size']) || ($this->upConfig['size']>0 && $attach['size']>$this->upConfig['size']))
			{
				$this->errorMsg = "lang:uploadOverMaxSize@@{$attach['name']}";
				return FALSE;
			}

			if (in_array($attach['ext'], array('jpg', 'jpeg', 'gif', 'png', 'swf', 'bmp')) && function_exists('getimagesize') && !@getimagesize($attach['tmp_name']))
			{
				$this->errorMsg = "lang:uploadInvalidFile@@{$attach['name']}";
				return FALSE;
			}
		}
		$this->fileNum = count($this->upData);
		return TRUE;
	}

	/**
	 * 删除上传的文件
	 * @return void
	 */
	public function DelFile()
	{
		if (!empty($this->fileList))
		{
			foreach ($this->fileList as $upfile)
			{
				@unlink($upfile['path'].'/'.$upfile['name']);
			}
		}
	}

	/**
	 * 生成新文件名
	 * @param $strFilename 原文件名
	 * @param $bolSuffix 是否为危险文件增加后缀名
	 * @return string 新文件名
	 */
	public function NewFilename($strFilename, $bolSuffix = FALSE)
	{
		$tempext = FileSystem::GetFileExt($strFilename, FALSE);
		if ($bolSuffix && is_array($this->upConfig['totype']) && !empty($this->upConfig['totype']) && in_array($tempext, $this->upConfig['totype']))
		{
			$tempext .= '.file';
		}
		return TimeDate::FormatTime(WEB_TIME, 'ymdHis').String::Random(6).'.'.$tempext;
	}

	/**
	 * 保存文件
	 * @param $strAbsPath 要保存的绝对路径
	 * @param $strFilePreFix 文件名前缀
	 * @param $bolBuildFilename 是否构建随机文件名 FALSE:按文件名前缀保存
	 * @param $bolSuffix 是否为危险文件增加后缀名
	 * @return void
	 */
	public function SaveFile($strAbsPath, $strFilePreFix = '', $bolBuildFilename = TRUE, $bolSuffix = TRUE)
	{
		$returnarray = array();
		if (substr($strAbsPath, -1)=='/')
		{
			$strAbsPath = substr($strAbsPath, 0, -1);
		}
		FileSystem::CreateFolder($strAbsPath);
		foreach ($this->upData as $key => $attach)
		{
			if ($strFilePreFix!='' && !$bolBuildFilename)
			{
				$savename = $strFilePreFix.($key>0 ? $key : '').FileSystem::GetFileExt($attach['name'], FALSE);
			}
			else
			{
				$savename = $strFilePreFix.$this->NewFilename($attach['name'], $bolSuffix);
			}
			$savefile = $strAbsPath.'/'.$savename;
			$filesaved = FALSE;

			if (@copy($attach['tmp_name'], $savefile) || (function_exists('move_uploaded_file') && @move_uploaded_file($attach['tmp_name'], $savefile)))
			{
				@unlink($attach['tmp_name']);
				$filesaved = TRUE;
			}

			if (!$filesaved && @is_readable($attach['tmp_name']))
			{
				@$fp = fopen($attach['tmp_name'], 'rb');
				@flock($fp, 2);
				@$attachedfile = fread($fp, $attach['size']);
				@fclose($fp);

				@$fp = fopen($savefile, 'wb');
				@flock($fp, 2);
				if (@fwrite($fp, $attachedfile))
				{
					@unlink($attach['tmp_name']);
					$filesaved = TRUE;
				}
				@fclose($fp);
			}

			if ($filesaved)
			{
				$returnarray[$key]['name'] = $savename;
				$returnarray[$key]['size'] = $attach['size'];
				$returnarray[$key]['type'] = FileSystem::GetFileExt($attach['name'], FALSE);
				$returnarray[$key]['oldname'] = $attach['name'];
				$returnarray[$key]['path'] = $strAbsPath;
				$returnarray[$key]['isimage'] = 0;
				$returnarray[$key]['width'] = 0;
				$returnarray[$key]['height'] = 0;
				if (in_array($returnarray[$key]['type'], array('jpg', 'jpeg', 'gif', 'png', 'swf', 'bmp')) && function_exists('getimagesize'))
				{
					$imagefileinfo = @getimagesize($savefile);
					if ($imagefileinfo!==FALSE)
					{
						$returnarray[$key]['width'] = $imagefileinfo[0];
						$returnarray[$key]['height'] = $imagefileinfo[1];
						if (in_array($imagefileinfo[2], array('1', '2', '3')))
						{
							$returnarray[$key]['isimage'] = 1;
						}
					}
				}
			}
		}
		$this->fileList = $returnarray;
	}

	/**
	 * 设置上传条件
	 * @param $aryConfig 上传参数配置
	 * @return void
	 */
	public function SetConfig($aryConfig)
	{
		if (is_array($aryConfig) && !empty($aryConfig))
		{
			foreach ($this->upConfig as $key => $value)
			{
				if (isset($aryConfig[$key]))
				{
					$this->upConfig[$key] = $aryConfig[$key];
				}
			}
		}
	}

	/**
	 * 设置上传控件获取数据
	 * @param $strInputName 上传的input名称
	 * @return void
	 */
	public function SetInput($strInputName)
	{
		$curData = Lfly::$webUpfile[$strInputName];
		if (is_array($curData))
		{
			foreach ($curData as $key => $value)
			{
				if (is_array($value))
				{
					foreach ($value as $id => $val)
					{
						$this->upData[$id][$key] = $val;
					}
				}
				else
				{
					$this->upData[0][$key] = $value;
				}
			}
		}
		foreach ($this->upData as $key => $value)
		{
			if (empty($value['name']) && empty($value['tmp_name']) && $value['size']==0)
			{
				unset($this->upData[$key]);
			}
		}
	}


	/*************************************************************************/


	/* 检测是否上传文件 */
	private function IsUploadedFile($strFile)
	{
		return function_exists('is_uploaded_file') && (is_uploaded_file($strFile) || is_uploaded_file(str_replace('\\\\', '\\', $strFile)));
	}

}	//end class

?>